<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

/**
 * 此中间件用于记录请求、响应日志。
 */
class LogRequest
{
    private $start = 0;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->start = microtime(true);
        return $next($request);
    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Http\Response $response
     */
    public function terminate($request, $response)
    {
        $duration = microtime(true) - $this->start;
        $url      = $request->fullUrl();
        $method   = $request->getMethod();
        $ip       = $request->getClientIp();
        $log      = "{$ip}: {$method}@{$url} - {$duration}ms \n".
                    "Request : ".$request->getContent()." ".($_FILES ? ", files: ".var_export($_FILES, true) : '') ." \n".
                    "Response : ".$response->getContent()." \n";
        Log::info($log);
    }
}
